<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="!dealId" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              parameters="deal"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="dealId" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <el-input v-model="dealBaseInfo.dealName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="pageUrl === 'fundToDealCashflowList'" :label="$t('承担主体')" prop="investorId">
            <el-select v-model="form.investorId" clearable filterable :placeholder="$t('承担主体')" disabled>
              <el-option
                v-for="investment in investmentList"
                :key="investment.id"
                :label="investment.investorName"
                :value="investment.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="pageUrl !== 'fundToDealCashflowList'" :label="$t('承担主体')" prop="investorId">
            <el-select v-model="form.investorId" filterable :placeholder="$t('承担主体')">
              <el-option
                v-for="investment in investmentList"
                :key="investment.id"
                :label="investment.investorName"
                :value="investment.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('现金流类型')" prop="type">
            <el-select v-model="form.type" filterable :placeholder="$t('现金流类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('业务类型')" prop="operateType">
            <el-select v-model="form.operateType" filterable :placeholder="$t('业务类型')">
              <el-option
                v-for="dict in operateTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('权益变更时间')" prop="equityChangeTime">
            <DatePicker v-model="form.equityChangeTime" :placeholder="$t('权益变更时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="operateDate">
            <DatePicker v-model="form.operateDate" :placeholder="$t('发生时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生金额') + $t('(元)')" prop="operateAmount">
            <money v-model="form.operateAmount" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <el-select v-model="form.currency" filterable :placeholder="$t('币种')">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="formatCurrencyByInvestDictValue(form.investorId) !== form.currency" :span="12">
          <el-form-item :label="$t('汇率')" prop="exchangeRate">
            <el-input-number v-model="form.exchangeRate" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col v-if="formatCurrencyByInvestDictValue(form.investorId) !== form.currency" :span="12">
          <el-form-item :label="$t('发生金额') + formatCurrencyByInvest(form.investorId) + $t('(元)')" prop="operateAmountRMB">
            <money v-model="form.operateAmountRMB" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('方向')" prop="direction">
            <el-radio-group v-model="form.direction">
              <el-radio
                v-for="dict in directionOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('是否参与IRR计算')" prop="whetherIrr">-->
        <!--            <el-radio-group v-model="form.whetherIrr">-->
        <!--              <el-radio-->
        <!--                v-for="dict in whetherIrrOptions"-->
        <!--                :key="dict.dictValue"-->
        <!--                :label="dict.dictValue"-->
        <!--              >{{ $t(dict.dictLabel) }}-->
        <!--              </el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('是否参与DPI计算')" prop="whetherIrr">-->
        <!--            <el-radio-group v-model="form.dpi">-->
        <!--              <el-radio-->
        <!--                v-for="dict in whetherIrrOptions"-->
        <!--                :key="dict.dictValue"-->
        <!--                :label="dict.dictValue"-->
        <!--              >{{ $t(dict.dictLabel) }}-->
        <!--              </el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col v-if="form.direction === 'LR'" :span="12">
          <el-form-item :label="$t('流入类型')" prop="incomeType">
            <el-radio-group v-model="form.incomeType">
              <el-radio
                v-for="dict in (($route.query.dealType === 'spo' && form.operateType === 'HK') ? incomeTypeOptionsSpo : incomeTypeOptions)"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="deal:cashflow" data-type="deal_cashflow" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div v-if="btnShow" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="deal:cashflow" />
    </div>
  </div>
</template>

<script>
    import { saveDealCashflow, getDealCashflow } from '@/api/deal/cashflow/dealCashflow'
    import { listDealInvestment } from '@/api/deal/investment/dealInvestment'
    import { getDealBase } from '@/api/base/deal/dealBase'
    import MainBodySelect from '@/components/MainBodySelect'
    export default {
      components: {
        MainBodySelect
      },
      props: {
        btnShow: {
          type: Boolean,
          default: true,
          desc: '是否展示按钮'
        }
      },
        data() {
            const moneyCheck = (rule, value, callback) => {
              if (value === 0 || value === '0') {
                callback(new Error(this.$t('不能为0')))
              } else if (value === '' || value === undefined || value === null) {
                 callback(new Error(this.$t('必填信息')))
              } else {
                callback()
              }
            }
            return {
              otherBtnHide: false,
              // 现金流类型  预计 实际字典
              typeOptions: [], // 方向：流入、流出字典
              directionOptions: [], // 类型：投资、回款、费用字典
              operateTypeOptions: [], // 是否参与IRR计算字典
              whetherIrrOptions: [], // 表单参数
              incomeTypeOptions: [], // 流入类型
              incomeTypeOptionsSpo: [], // 定增项目回款的流入类型
              currencyOptions: [],
              form: {
                fileList: []
              },
              // 当前项目信息
              dealBaseInfo: {},
              // 项目ID
              pageUrl: this.$route.query.menuPath,
              dealId: this.$route.query.menuPath !== 'fundToDealCashflowList' ? this.$route.query.id : undefined,
              fundId: this.$route.query.menuPath === 'fundToDealCashflowList' ? this.$route.query.id : undefined,
              // 项目投资主体列表
              investmentList: [],
              // 根据使用场景来决定显示选择项目还是显示当前项目
              isShowDeal: !this.dealId,
              // 遮罩层
              loading: false,
              // 表单校验
              rules: {
                type: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], dealId: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], operateDate: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], operateAmount: [
                  { required: true, validator: moneyCheck, trigger: 'blur' }
                ], currency: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], operateType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], direction: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], whetherIrr: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], incomeType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], equityChangeTime: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ]
              }
            }
        },
        watch: {
          'form.dealId': {
            handler(val) {
              this.investmentList = undefined
              this.investorId = undefined
              listDealInvestment({ 'dealId': val }).then(response => {
                this.investmentList = response.rows
              })
            }
          }
        },
        created() {
            this.getDicts('cash_flow_type').then(response => {
                this.typeOptions = response.data
            })
            this.getDicts('cash_flow_direction').then(response => {
                this.directionOptions = response.data
            })
            this.getDicts('deal_cash_flow_type' + (this.$route.query.dealType === 'spo' ? '_spo' : '')).then(response => {
                this.operateTypeOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
                this.whetherIrrOptions = response.data
            })
            // 流入类型字典
            this.getDicts('income_type').then(response => {
              this.incomeTypeOptions = response.data
            })
            // 定增流入类型字典
            this.getDicts('deal_cash_flow_lrlc_spo').then(response => {
              this.incomeTypeOptionsSpo = response.data
            })
            this.getDicts('currency').then(response => {
              this.currencyOptions = response.data
            })
            /* listDealInvestment({ 'dealId': this.form.dealId }).then(response => {
              this.investmentList = response.rows
            }) */
        },
        mounted() {
          this.$bus.$emit('async_done')
        },
        methods: {
          // 初始化数据
          init(data) {
            debugger
            this.loading = true
            if (data != null && data.id !== undefined) {
              getDealCashflow(data.id).then(response => {
                if (response.data && response.data.investorId == null) {
                  response.data.investorId = undefined
                }
                this.form = response.data
                getDealBase(this.form.dealId).then(response => {
                  this.dealBaseInfo = response.data
                })
                this.loading = false
              })
            } else {
              this.reset()
              this.loading = false
            }
          },
            // 表单重置
            reset() {
                this.form = {
                  id: undefined,
                  type: undefined,
                  dealId: this.$route.query.id,
                  dataId: undefined,
                  component: undefined,
                  investorId: undefined,
                  operateDate: undefined,
                  equityChangeTime: undefined,
                  operateAmount: 0,
                  currency: 'CNY',
                  exchangeRate: 0,
                  operateAmountRMB: 0,
                  direction: undefined,
                  operateType: undefined,
                  whetherIrr: 'Y',
                  dpi: 'Y',
                  incomeType: '',
                  fileList: [],
                  remark: undefined,
                  createBy: undefined,
                  createTime: undefined,
                  updateBy: undefined,
                  updateTime: undefined,
                  delFlag: undefined
                }
              if (this.form.dealId !== undefined) {
                getDealBase(this.form.dealId).then(response => {
                  this.dealBaseInfo = response.data
                })
              }

                this.resetForm('form')
            },
            formatCurrencyByInvest(val) {
              console.log('汇率对应币种')
              if (this.investmentList !== undefined) {
                const find = this.investmentList.find(obj => obj.id === val)
                if (find) {
                  return ' - ' + this.formatCurrency(find.currency)
                }
              }
              return ''
            },
            formatCurrencyByInvestDictValue(val) {
              if (this.investmentList !== undefined) {
                const find = this.investmentList.find(obj => obj.id === val)
                if (find) {
                  return find.currency
                }
              }
              return 'CNY'
            },
            formatCurrency(val) {
              const currency = this.currencyOptions.find(obj => obj.dictValue === val)
              if (currency) {
                return currency.dictLabel
              }
              return val
            },
            // 取消按钮
            cancel() {
              // if (this.$parent.$parent.homeOpen) {
              //    this.$parent.$parent.homeOpen = false
              //    this.reset()
              // } else {
              //   this.$parent.$parent.formOpen = false
              //   this.$parent.$parent.reset()
              // }
              if (this.$parent.$parent.$parent.cashflowOpen) {
                this.$parent.$parent.$parent.cashflowOpen = false
              }
              if (this.$parent.$parent.formOpen) {
                this.$parent.$parent.formOpen = false
              }
              if (this.$parent.$parent?.reset !== undefined) {
                this.$parent.$parent.reset()
              }
            },
            // 关闭form页面
            closeForm() {
              this.loading = false
              if (this.$parent.$parent.$parent.cashflowOpen) {
                this.$parent.$parent.$parent.cashflowOpen = false
              }
              if (this.$parent.$parent.formOpen) {
                this.$parent.$parent.formOpen = false
              }
              if (this.$parent.$parent?.reset !== undefined) {
                this.$parent.$parent.reset()
              }
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
              // if (this.$parent.$parent.homeOpen) {
              //    this.$parent.$parent.homeOpen = false
              //    this.reset()
              // } else {
              //   this.$parent.$parent.formOpen = false
              //   this.$parent.$parent.getList()
              // }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                      if (!(this.formatCurrencyByInvestDictValue(this.form.investorId) !== this.form.currency)) {
                        this.form.exchangeRate = 1
                        this.form.operateAmountRMB = this.form.operateAmount
                      }
                        saveDealCashflow(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                                this.loading = false
                            }
                        }).catch(() => {
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           }
        }
    }
</script>
